package config

import (
	"bytes"
	"encoding/json"
	"fmt"
	fun "gitee.com/jishulang/go-fun"
	"github.com/BurntSushi/toml"
	"gopkg.in/yaml.v3"
)

func configCreateFile(conf interface{}, configType string) {
	filePath := fmt.Sprintf("%s/%s.%s", CONFIG_DIR, SETTINGS_NAME, configType)
	is, _ := fun.FileIsExist(filePath)
	if !is {
		content := structToConfigType(conf, configType)
		fun.FilePutContents(filePath, content)
	}

	//
	for _, e := range envArr {
		filePath = fmt.Sprintf("%s/%s_%s.%s", CONFIG_DIR, SETTINGS_NAME, e, configType)
		is, _ = fun.FileIsExist(filePath)
		if !is {
			//content := structToConfigType(conf, configType)
			content := contentDefaultValue(configType)
			fun.FilePutContents(filePath, content)
		}
	}
}

func contentDefaultValue(configType string) string {
	switch configType {
	case CONFIG_TYPE_YAML, CONFIG_TYPE_YML:

	case CONFIG_TYPE_JSON:
		return "{}"
	case CONFIG_TYPE_TOML:

		//case "properties":
		//case "props":
		//case "hcl":
		//case "tfvars":
		//case "dotenv":
		//case "env":
		//case "ini":
	}

	return ""
}

func structToConfigType(conf interface{}, configType string) string {
	var jsonBytes []byte
	var err error
	switch configType {
	case CONFIG_TYPE_YAML, CONFIG_TYPE_YML:
		jsonBytes, err = structToYaml(conf)
	case CONFIG_TYPE_JSON:
		jsonBytes, err = structToJson(conf)
	case CONFIG_TYPE_TOML:
		jsonBytes, err = structToToml(conf)
		//case "properties":
		//case "props":
		//case "hcl":
		//case "tfvars":
		//case "dotenv":
		//case "env":
		//case "ini":
	}

	if err != nil {
		fmt.Println("[NewConfig]structToConfigType err:", err.Error())
		return ""
	}

	return string(jsonBytes)
}

func structToJson(conf interface{}) ([]byte, error) {
	return json.MarshalIndent(conf, "", "  ")
}

func structToToml(conf interface{}) ([]byte, error) {
	var tomlBuffer bytes.Buffer
	err := toml.NewEncoder(&tomlBuffer).Encode(conf)
	if err != nil {
		return nil, err
	}
	return tomlBuffer.Bytes(), nil
}

func structToYaml(conf interface{}) ([]byte, error) {
	return yaml.Marshal(conf)
}
